
package com.itfenghuang.day14;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class A05_ClientChat {
    public static void main(String[] args) throws IOException {
        /**
         *  1.创建Socket
         *  2.控制台输入聊天消息
         *  3.接收  nextLine()
         *  4.获取输出流 getOutputStream
         *  5.死循环   3和4
         *  6.接收控制台消息并发送到服务端需要一个线程
         */

        Scanner sc = new Scanner(System.in);
        Socket socket = new Socket("127.0.0.1",10086);
        //获取输出流,用来写出数据
        OutputStream os = socket.getOutputStream();
        //转换流   OutputStreamWriter
        //字符缓冲输出流
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

        //接收控制台消息并发送到服务端的线程
        //接收控制台消息  将消息发送到服务端
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                        System.out.println("请输入要发送的消息");
                        String line = sc.nextLine();
                        try {
                            bw.write(line);
                            bw.newLine();//写出一个换行符
                            bw.flush();//刷新缓冲区
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                }
            }
        }).start();

        //获取输入流
        InputStream is = socket.getInputStream();
        //字符缓冲输入流
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        //接收服务端回送的消息,并在控制台打印输出
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        String s = br.readLine();
                        System.out.println(s);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }
}
